//
//  LLListenViewController.m
//  ListenAndLook
//
//  Created by zhangtao on 15/10/21.
//  Copyright © 2015年 zt.td. All rights reserved.
//

#import "LLListenViewController.h"
#import "LLLookViewController.h"
#import "LoginAndRegistViewController.h"
#import "Share.h"
typedef enum {
    Pre      =    0,
    Next     =    1,
    FOR_ONE  =    3,
    O_O      =    4,
    
}PreAndNext;


static void *PlayViewCMTimeValue = &PlayViewCMTimeValue;
static void *AVPlayerDemoPlaybackViewControllerStatusObservationContext = &AVPlayerDemoPlaybackViewControllerStatusObservationContext;


@interface LLListenViewController()

@property(nonatomic,strong)NSString *coverImg;

@property (unsafe_unretained, nonatomic) IBOutlet UIButton *nextBtn;
@property (strong, nonatomic) IBOutlet UIImageView *headerIV;

@property (weak, nonatomic) IBOutlet UILabel *headerLabel;
@property (strong, nonatomic) IBOutlet UIImageView *titleIV;

@property (strong, nonatomic) IBOutlet UIButton *playAndPause;
@property (weak, nonatomic) IBOutlet UIButton *shoucang;

@property(nonatomic,strong)NSString *sel;

@property(nonatomic,strong)NSArray *musicArray;
@property(nonatomic,strong)NSString *urlStr;
@property(nonatomic,assign)NSInteger count;
@property(nonatomic,assign)float mix;
@property(nonatomic,assign)float max;
@property(nonatomic,assign)float value;

@property(nonatomic,strong)NSString *bookId;

//@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loading;
@property(nonatomic,strong)NSString *isShoucang;
@property(nonatomic,assign)BOOL is_type;
//@property(nonatomic,strong)NSString *flag;
//@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//播放器
@property (weak, nonatomic) IBOutlet UIButton *fresh;

@end

@implementation LLListenViewController
- (IBAction)rightBtn:(id)sender {
    [ToolObjc showMessage:@"亲，你点我了 "];
}

//-(void)viewWillDisappear:(BOOL)animated{
////    [self removePlayerTime Observer];
////    self.player = nil;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
//    {
    
    
    _a.layer.borderColor = _b.layer.borderColor  = [[UIColor colorWithRed:230/255.f green:230/255.f blue:230/255.f alpha:1]CGColor];
    _a.layer.borderWidth = _b.layer.borderWidth =  1;

    
    
    
    self.is_type = YES;
//    [_mySliter addTarget:self action:@selector(sliterChange) forControlEvents:UIControlEventTouchUpInside];
    _mySliter.minimumTrackTintColor = [UIColor yellowColor];
    _mySliter.maximumTrackTintColor = RGB(230, 230, 230, 1); //[UIColor grayColor];
//    _mySliter.value = 0;
//    UIImage *image = [UIImage imageNamed:@"item_selected"];
//    
//    [_mySliter setThumbImage:[UIImage imageNamed:@"sliders.png"] forState:UIControlStateNormal];
    _mySliter.thumbTintColor = [UIColor clearColor];

    [_mySliter setThumbImage:[UIImage imageNamed:@"middle.png"] forState:UIControlStateNormal];

//}

//
    [self request];
    
    
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    [session setActive:YES error:nil];
//    
//    [_player setVolume:1];

    
//    [self player];
    _count = 0;

//    }
}


-(void)initPlay{
    NSString *path = _audioUrl;
    NSURL *sourceMovieURL = [NSURL URLWithString:path];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
    self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];

    self.mySliter.minimumValue = 0.0;
    self.mySliter.maximumValue = CMTimeGetSeconds(movieAsset.duration);
    self.mySliter.value = 0.0;//指定初始值
    [self.mySliter addTarget:self action:@selector(updateValue:) forControlEvents:UIControlEventTouchUpInside];//设置响应
    [self.playerItem addObserver:self
                      forKeyPath:@"status"
                         options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                         context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];
    [self initScrubberTimer];

}




- (double)duration
{
    AVPlayerItem *playerItem = [[self player] currentItem];
    
    if ([playerItem status] == AVPlayerItemStatusReadyToPlay)
        return CMTimeGetSeconds([[playerItem asset] duration]);
    else
        return 0.f;
}

- (double)currentTime
{
    return CMTimeGetSeconds([[self player] currentTime]);
}

- (void)setCurrentTime:(double)time
{
    [[self player] seekToTime:CMTimeMakeWithSeconds(time, 1)];
}

- (void)PlayOrPause{
    
    if ([[self player] rate] != 1.f) {
        if ([self currentTime] == [self duration])
            [self setCurrentTime:0.f];
        [[self player] play];
    } else {
        [[self player] pause];
    }
    
//    CMTime time = [self.player currentTime];
//    NSLog(@"%lld",self.playerItem.duration.value/self.playerItem.duration.timescale);
//    NSLog(@"%lld",time.value/time.timescale);
    
}



#pragma mark - slider
- (void)updateValue:(UISlider *)slider{
    
    [self.player seekToTime:CMTimeMakeWithSeconds(slider.value, 1)];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    /* AVPlayerItem "status" property value observer. */
    if (context == AVPlayerDemoPlaybackViewControllerStatusObservationContext)
    {
        
        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        switch (status)
        {
                /* Indicates that the status of the player is not yet known because
                 it has not tried to load new media resources for playback */
            case AVPlayerStatusUnknown:
            {
                
            }
                break;
                
            case AVPlayerStatusReadyToPlay:
            {
                /* Once the AVPlayerItem becomes ready to play, i.e.
                 [playerItem status] == AVPlayerItemStatusReadyToPlay,
                 its duration can be fetched from the item. */
                
                [self initScrubberTimer];
                
            }
                break;
                
            case AVPlayerStatusFailed:
            {
                
            }
                break;
        }
    }
    
}

#pragma  maik - 监听
-(void)initScrubberTimer
{
    double interval = .1f;
    
    CMTime playerDuration = [self playerItemDuration];
    if (CMTIME_IS_INVALID(playerDuration))
    {
        return;
    }
    double duration = CMTimeGetSeconds(playerDuration);
    if (isfinite(duration))
    {
        CGFloat width = CGRectGetWidth([self.mySliter bounds]);
        interval = 0.5f * duration / width;
    }
    NSLog(@"interva === %f",interval);
    
    __weak typeof(self) weakSelf = self;
    
    /* Update the scrubber during normal playback. */
    [weakSelf.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(interval, NSEC_PER_SEC)
                                                  queue:NULL /* If you pass NULL, the main queue is used. */
                                             usingBlock:^(CMTime time)
     {
         [self syncScrubber];
     }];
    
}

/* Set the scrubber based on the player current time. */
- (void)syncScrubber
{
//    NSLog(@"syncScrubber");
    CMTime playerDuration = [self playerItemDuration];
    if (CMTIME_IS_INVALID(playerDuration))
    {
        self.mySliter.minimumValue = 0.0;
        return;
    }
    
    double duration = CMTimeGetSeconds(playerDuration);
    if (isfinite(duration))
    {
        float minValue = [self.mySliter minimumValue];
        float maxValue = [self.mySliter maximumValue];
        double time = CMTimeGetSeconds([self.player currentTime]);
//        NSLog(@"时间 :: %f",(maxValue - minValue) * time / duration + minValue);
        [self.mySliter setValue:(maxValue - minValue) * time / duration + minValue];
    }
}

- (CMTime)playerItemDuration
{
    AVPlayerItem *playerItem = [self.player currentItem];
//    NSLog(@"%ld",playerItem.status);
    if (playerItem.status == AVPlayerItemStatusReadyToPlay)
    {
        return([playerItem duration]);
    }
    
    return(kCMTimeInvalid);
}








- (IBAction)changeToLook:(id)sender {
    LLLookViewController *lookVC = [[LLLookViewController alloc]initWithNibName:@"LLLookViewController" bundle:nil];
    lookVC.lll = self;
    lookVC.passText = self.text;
    lookVC.coverImg = self.coverImg;
    [lookVC timer];
    [self presentViewController:lookVC animated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//上一首下一首
- (IBAction)preAndNextBtn:(UIButton *)sender {
    
    if (sender.tag == Pre) {
        [self  allFor:@"prev"];
        //        NSLog(@"pre::::::%@");
    }else{
        [self allFor:@"next"];
        //               NSLog(@"next::::");
    }
    
  
}

- (IBAction)fresh:(id)sender {
   

    if ((_is_type)) {
        _is_type = NO;
         [[NSNotificationCenter defaultCenter] removeObserver:self];
        
        [_fresh setImage:[UIImage imageNamed:@"Repeat-2-拷贝"]  forState:UIControlStateNormal];
        [ToolObjc showMessage:@"单曲循环"];
         [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(runLoopTheMovie:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
        _mySliter.value = 0;
        [self updateValue:_mySliter];

    }
    else{
         [[NSNotificationCenter defaultCenter] removeObserver:self.playerItem];
        _is_type = YES;
        [_fresh setImage:[UIImage imageNamed:@"Repeat-2"] forState:UIControlStateNormal];
        [ToolObjc showMessage:@"自动下一首"];
        [self nextSing];
    }
   

}

-(void)nextSing{
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
}

-(void)runLoopTheMovie:(NSNotification *)no{
      [self.playerItem seekToTime:kCMTimeZero];
    [self.player play];
}

-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
    [self allFor:@"next"];
    [self.player play];
}



- (IBAction)playAndPause:(id)sender {

        if(self.player.rate==0){ //说明时暂停
            [sender setImage:[UIImage imageNamed:@"stop"] forState:UIControlStateNormal];
            [self.player play];
        }else if(self.player.rate==1){//正在播放
            [self.player pause];
            [sender setImage:[UIImage imageNamed:@"start_2.png"] forState:UIControlStateNormal];
        }
}


#pragma mark - 监控

- (IBAction)back:(id)sender {
//    _audioPlayer = nil;
    _player = nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
    [self removeObserver:self.player.currentItem forKeyPath:@"state"];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
   
    
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];

}


-(void)request{
   
//    {
//        _loading.hidden = NO;
//        _loading.backgroundColor = [UIColor grayColor];
//        [_loading setTintColor:[UIColor grayColor]];
//        _loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
//        [_loading startAnimating];
//    }
    [[MBProgressController sharedInstance]showWithText:@"正在加载"];

    
    NSString *path = @"listenWatch/getBookTextById";
    
    NSString *userId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"USERID")];
   
    NSMutableDictionary *dics = [NSMutableDictionary dictionaryWithObjectsAndKeys:userId,@"userId",_idValue,@"bookTextId", nil];
    

    [[HttpConnctionManager sharedInstance]requestParam:MD5 andUrl:path andSuccessedBlock:^(NSDictionary *succeedResult) {
//
        _headerLabel.text = _textName.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"textName"];
        _author.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"author"];
        
        _audioUrl = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"audioUrl"];

        NSString *pic = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"cover"];
        self.coverImg = pic;
        _bookId = [NSString stringWithFormat:@"%@",[[succeedResult valueForKey:@"resData"]stringWithFilted:@"bookId"]];
       
        
        _text =[NSString stringWithFormat:@"%@",[[succeedResult valueForKey:@"resData"]stringWithFilted:@"text"]];
//
        
        NSString *shouchang = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"isCollection"];
        _isShoucang = shouchang;
        if ([_isShoucang isEqualToString:@"0"]) {
            [_shoucang setImage:[UIImage imageNamed:@"save.png"] forState:UIControlStateNormal];
        }else{
            [_shoucang setImage:[UIImage imageNamed:@"save_1.png"] forState:UIControlStateNormal];
        }
        [self initPlay];
        [self.player play];
        [self nextSing];
        
        NSURL *url = [NSURL URLWithString:pic];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        if (!image) {
            _textPictureUrl.image = _headerIV.image= [UIImage imageNamed:@"小书"];

        }else{
        _textPictureUrl.image = _headerIV.image= image;
        //
        
        }
        
//        _loading.hidden = YES;
//        [_loading stopAnimating];
        [[MBProgressController sharedInstance]hide];
        
        
    } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
        //
    }];
}


- (IBAction)shoucang:(id)sender {
    
    
    NSString *path = @"listenWatch/bookTextCollection";
    
     NSString *userId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"USERID")];
    NSDictionary *dic = @{@"bookTextId":_idValue,@"userId":userId};
    NSDictionary *dics = @{@"bookTextId":_idValue,@"userId":userId,@"bd_sig":[ToolObjc md5Str:dic]};
    NSLog(@"%@",dics);
    [[HttpConnctionManager sharedInstance]requestParam:dics andUrl:path andSuccessedBlock:^(NSDictionary *succeedResult) {

        if ([_isShoucang isEqualToString:@"0"]) {
            _isShoucang = @"1";
            [_shoucang setImage:[UIImage imageNamed:@"save_1.png"] forState:UIControlStateNormal];
            [ToolObjc showMessage:@"收藏成功"];

        }else{
            _isShoucang = @"0";
            [_shoucang setImage:[UIImage imageNamed:@"save.png"] forState:UIControlStateNormal];
            [ToolObjc showMessage:@"取消收藏"];

        }

//        if ([rescode isEqualToString:@"0"]) {
//        }
        
    } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
        
    }];
    
}

-(void)allFor:(NSString *)tpye{
    
    
//    {
//        
//        _loading.hidden = NO;
//        _loading.backgroundColor = [UIColor grayColor];
//        [_loading setTintColor:[UIColor grayColor]];
//        _loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
//        [_loading startAnimating];
//    }
//    [[MBProgressController sharedInstance]showWithText:@"正在加载"];
    
    NSString *path = @"listenWatch/getPrevAndNextBookText";
    
    NSString *userId = [NSString stringWithFormat:@"%@",NSUSER_DEF(@"USERID")];
    NSString *bookTextId = _idValue;
    NSString *flag = tpye; ;//= @"prev";
    NSDictionary *dicss;
    NSDictionary *dicVal;
    
    if (!_bookId) {
        [ToolObjc showMessage:@"暂无相关信息"];
    }else{
        
        
        dicss = @{@"bookTextId":bookTextId,@"userId":userId,@"bookId":_bookId,@"flag":flag};
        NSLog(@"dicss%@",dicss);
        
        NSLog(@"111");
        NSString *bd = [ToolObjc md5Str:dicss];
        
        dicVal = @{@"bookTextId":bookTextId,@"userId":userId,@"bookId":_bookId,@"flag":flag,@"bd_sig":bd};
        
        
        [[HttpConnctionManager sharedInstance]requestParam:dicVal andUrl:path andSuccessedBlock:^(NSDictionary *succeedResult) {
            if ([[NSString stringWithFormat:@"%@",[succeedResult valueForKey:@"resCode"] ]isEqualToString:@"1"]) {
                [ToolObjc showMessage:@"暂无相关信息"];
                
            }
            
            else{
                
                _headerLabel.text = _textName.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"textName"];
                _author.text = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"author"];
                
                _audioUrl = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"audioUrl"];
                
                NSString *pic = [[succeedResult valueForKey:@"resData"]stringWithFilted:@"cover"];
                _text =[NSString stringWithFormat:@"%@",[[succeedResult valueForKey:@"resData"]stringWithFilted:@"text"]];
                
                _bookId =[NSString stringWithFormat:@"%@", [[succeedResult valueForKey:@"resData"]stringWithFilted:@"bookId"]];
                NSLog(@"%@",_audioUrl);
                
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:pic]]];
                _textPictureUrl.image = _headerIV.image= image;
                self.coverImg = pic;
                //        _player=[AVPlayer playerWithPlayerItem:_playerItem];
                
               
                
                [self.playerItem removeObserver:self forKeyPath:@"status"];
                
                //            [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
                //            [self.player replaceCurrentItemWithPlayerItem:_playerItem];
                
                NSString *path = _audioUrl;
                NSURL *sourceMovieURL = [NSURL URLWithString:path];
                AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];
                self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
                
                _player=[AVPlayer playerWithPlayerItem:_playerItem];
                
                [self.playerItem addObserver:self
                                  forKeyPath:@"status"
                                     options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                                     context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];
                [self.player replaceCurrentItemWithPlayerItem:_playerItem];
                            [self.player play];
                
//                _mySliter.value = 0;
//                
//                [self updateValue:_mySliter];
//                
                
            }
//            _loading .hidden = YES;
//            [_loading stopAnimating];
        } andFailedBlock:^(AFHTTPRequestOperation *response, NSError *error) {
            
        }];
//        [[MBProgressController sharedInstance]hide];

    }
    dicss = nil;
    dicVal = nil;

    
}


- (IBAction)share:(id)sender {
    
    
    [Share WeChatShare];
}

/**


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
